package com.chat.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chat.system.entity.dto.ApplicationDTO;
import com.chat.system.entity.dto.ChatUserDTO;
import com.chat.system.entity.po.ChatUser;
import com.chat.system.entity.po.ChatUserApplication;
import com.chat.system.entity.po.ChatUserRelationship;
import com.chat.system.mapper.ChatUserApplicationMapper;
import com.chat.system.service.IChatUserApplicationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chat.system.service.IChatUserRelationshipService;
import com.chat.system.service.IChatUserService;
import com.chat.system.utils.UserUtil;
import com.chat.wesocket.entity.WsMessage;
import com.chat.wesocket.handler.WsHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author czh
 * @since 2023-10-28
 */
@Service
public class ChatUserApplicationServiceImpl extends ServiceImpl<ChatUserApplicationMapper, ChatUserApplication> implements IChatUserApplicationService {

    @Autowired
    IChatUserService chatUserService;
    @Autowired
    IChatUserRelationshipService chatUserRelationshipService;

    @Autowired
    WsHandler wsHandler;
    @Override
    public boolean addNewApplication(String from, String to) throws IOException {
        //是否存在要申请的朋友
        QueryWrapper<ChatUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",to);
        final boolean exists = chatUserService.exists(queryWrapper);
        if ( !exists ) {
            return false;
        }
//是否已经申请了 并且对方未查看
        QueryWrapper<ChatUserApplication> applicationQueryWrapper = new QueryWrapper<>();

        applicationQueryWrapper.eq("_from",from).eq("_to",to).and(x -> {
            x.eq("status",ChatUserApplication.NOT_DONE).or().eq("status",ChatUserApplication.ACCEPT);
        });

//        queryWrapper.eq("_from",from).and(x -> x.eq("_to",to)).and(x -> x.eq("status",ChatUserApplication.NOT_DONE));
        final boolean applied = exists(applicationQueryWrapper);
        if (applied) {
            return false;
        }
        //TODO 如果双方同时申请则直接添加好友


        ChatUserApplication chatUserApplication = new ChatUserApplication(from,to);
        final boolean save = save(chatUserApplication);
        if(save) {
            final WebSocketSession online = wsHandler.isOnline(to);
            if (online != null) {
                WsMessage wsMessage = new WsMessage(WsMessage.EVENT_NEW_APPLICATION);
                wsMessage.put("message","好友申请");
                wsMessage.put("applier",from);
                wsMessage.put("appId",chatUserApplication.getId());
                online.sendMessage(wsMessage.toMessage());
            }
        }
        return save;
    }

    @Transactional
    @Override
    public void  confirm(String id,String status) {
        final ChatUserApplication application = getById(id);
        if (application == null) {
            throw new RuntimeException("搞事情你");
        }
        if (!application.getStatus().equals(ChatUserApplication.NOT_DONE) ) {
            throw new RuntimeException("搞事情你");
        }
        application.setStatus(status);
        updateById(application);
        if (application.getStatus().equals(ChatUserApplication.ACCEPT)) {
            ChatUserRelationship chatUserRelationship = new ChatUserRelationship();
            chatUserRelationship.setResPath("test");

            chatUserRelationship.setUserName(application.getFrom());
            chatUserRelationship.setFriendName(application.getTo());
            chatUserRelationshipService.save(chatUserRelationship);
            //TODO 通知
            final String from = application.getFrom();
            final String to = application.getTo();
            final WebSocketSession applier = wsHandler.isOnline(from);
            final WebSocketSession appliee = wsHandler.isOnline(to);

            WsMessage wsMessage = new WsMessage(WsMessage.EVENT_NEW_FRIEND_RELATION_ESTABLISH);
            wsMessage.put("relationship",chatUserRelationship);
            if (applier != null) {
                try {
                    applier.sendMessage(wsMessage.toMessage());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (appliee != null) {
                try {
                    appliee.sendMessage(wsMessage.toMessage());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }else {
            //
        }
    }

    @Override
    public List<ApplicationDTO> getApplication(String userName) {
        QueryWrapper<ChatUserApplication> applicationQueryWrapper = new QueryWrapper<>();
        applicationQueryWrapper.eq("_to",userName).eq("status",ChatUserApplication.NOT_DONE);
        final List<ChatUserApplication> applications = list(applicationQueryWrapper);
        List<ApplicationDTO> applicationDTOS = new ArrayList<>(applications.size());
        for (ChatUserApplication application : applications) {
            final String from = application.getFrom();
            applicationDTOS.add(new ApplicationDTO(application.getId(),from));
        }
        return applicationDTOS;
    }
}
